<template>
  <view>
    <van-tabs v-model="carType" @change="changeTab" sticky>
      <van-tab
        v-for="n in navList"
        :title="n.carName"
        :name="n.id"
        v-bind:key="n.id"
      >
        <div>
          <van-image
            width="10rem"
            height="10rem"
            fit="contain"
            :alt="n.carName"
            :src="n.carImg"
            rel="external nofollow"
            default="carRemark"
          />
          <span class="img-rek">{{ carRemark }}</span>
        </div>
      </van-tab>
    </van-tabs>

    <van-cell-group inset>
      <van-cell
        :title="startPlace.addDetail"
        :label="startPlace.city"
        icon="location-o"
        is-link
      >
        <van-field
          v-model="phone"
          type="text"
          @blur="phoneSet"
          required="true"
          placeholder="手机号"
          :rules="[{ required: true, message: '请填写手机号' }]"
        />
      </van-cell>
      <span class="start-place-click" @click="startChange"></span>

      <van-row
        class="midd-1"
        v-for="(point, index) in passPoints"
        v-bind:key="index"
        gutter="10px"
        style=""
      >
        <van-col span="20" offset="2">
          <van-cell :title="point.addr" :label="point.name" />
        </van-col>
        <van-icon
          name="close"
          @click="removePassPoint(index)"
          style="margin-top: 14px"
        />
      </van-row>

      <van-cell
        :title="endPlace_s"
        :label="endPlace_s_s"
        icon="location-o"
        is-link
        @click="selExprPoint"
      ></van-cell>
      <van-cell title="请规划好途径卸货地，以便估算价格" size="20px">
        <van-button type="primary" size="small" @click="addPassPoint"
          >+ 添加卸货地</van-button
        >
      </van-cell>
    </van-cell-group>

    <van-cell-group>
      <van-row>
        <van-col span="8"
          ><van-cell
            title="服务时间"
            required="true"
            icon="clock-o"
            class="server-time"
        /></van-col>
        <van-col span="8">
          <DateTimePicker
            :selBtnName="serverTimeBtn"
            @datetime="setServerTime"
          ></DateTimePicker>
        </van-col>
      </van-row>

      <van-row>
        <van-col span="8">
          <van-cell
            title="承载类型"
            required="true"
            icon="logistics"
          ></van-cell>
        </van-col>
        <van-col span="12">
          <van-row gutter="20">
            <van-radio-group
              :value="loadingType"
              @change="loadingTypeChange"
              class="radio-line"
            >
              <van-col span="10">
                <van-radio name="1">整车</van-radio>
              </van-col>
              <van-col span="10">
                <van-radio name="2">拼车</van-radio>
              </van-col>
            </van-radio-group>
          </van-row>
        </van-col>
      </van-row>
    </van-cell-group>

    <van-sticky :offset-bottom="10" position="bottom">
      <van-button type="default" class="submit-btn" @click="submitClick"
        >提交订单</van-button
      >
    </van-sticky>
  </view>
</template>
<script type="module">
import moment from "moment";
import utils from "@/utils/index.js";
import store from "@/utils/store.js";
import DateTimePicker from "@/components/DateTimePicker.vue";

let qqmapsdk;
var a = require;
const QQMapWX = a("../../../utils/qqmap-wx-jssdk.min.js");
export default {
  config: {
    navigationBarTitleText: "好家帮",
  },
  components: { DateTimePicker },
  data() {
    return {
      navList: [
        { carName: "三轮车", id: 1, carImg: "" },
        { carName: "面包车", id: 2, carImg: "" },
        { carName: "4.2米货车", id: 3, carImg: "" },
        { carName: "小型货车", id: 4, carImg: "" },
      ],
      activeNav: 0,
      passPoints: new Array(),
      serverTimeBtn: "请选择服务时间",
      startPlace: {
        longitude: 0, //经度
        latitude: 0, //纬度
        city: "",
        addDetail: "",
      },
      endPlace: {
        longitude: 0, //经度
        latitude: 0, //纬度
        city: "",
        addDetail: "请选择收获地址",
      },
      endPlace_s: "请补充收货地址信息",
      endPlace_s_s: "",
      serverTime: "",
      phone: "",
      carType: 1,
      loadingType: 0,
      carTypeImg: "",
      carRemark: "",
    };
  },
  watch: {
    endPlace: function (newData, oldData) {
      console.log("newData>>", newData, "oldData>>", oldData);
    },
  },
  computed: {
    user() {
      return store.state.user;
    },
    token() {
      return store.state.token;
    },
    count() {
      return store.state.count;
    },
    targetPoint() {
      return store.state.targetPoint;
    },
    carTypeList() {
      return store.state.trucks;
    },
  },
  methods: {
    selExprPoint() {
      const url = "../exprPoint/index";
      console.log("url", url);
      wx.navigateTo({ url });
    },
    startChange(event) {
      console.log("event", event);

      let that = this;
      let promise = this.selectMapPoint();

      promise
        .then(function (res) {
          console.log("res>>", res);

          that.startPlace.addDetail = res.addDetail;
          that.startPlace.longitude = res.longitude;
          that.startPlace.latitude = res.latitude;
          that.startPlace.city = res.city;
        })
        .catch(function (error) {
          console.error("error", error);
        });
    },
    phoneSet(event) {
      console.log("event", event);
      this.phone = event.mp.detail.value;
    },
    loadingTypeChange(event) {
      console.log("event", event);
      this.loadingType = event.mp.detail;
    },
    setServerTime(date) {
      this.serverTime = moment(date).format("YYYY-MM-DD hh:mm:ss");
      console.log("setServerTime date", date, "---", this.serverTime);
    },
    changeTab(event) {
      this.carType = event.target.name;

      let selType = this.carTypeList[this.carType - 1];
      this.carRemark = selType.remark;
      console.log("carType>>", this.carType, selType);
    },

    submitClick() {
      let s_mapPoint = {
        addDetail: this.startPlace.addDetail,
        city: "",
        district: "",
        province: "",
        longitude: this.startPlace.longitude,
        latitude: this.startPlace.latitude,
      };

      let mapPoints = new Array();
      mapPoints.push(s_mapPoint);

      this.passPoints.forEach((item) => {
        mapPoints.push({
          addDetail: item.addDetail,
          city: item.addr,
          district: item.dist,
          province: "",
          longitude: item.longitude,
          latitude: item.latitude,
        });
      });

      let e_mapPoint = {
        addDetail: this.endPlace.addDetail,
        city: "",
        district: "",
        province: "",
        latitude: this.endPlace.latitude,
        longitude: this.endPlace.longitude,
      };
      mapPoints.push(e_mapPoint);

      let orderSubmit = {
        mapPoints: mapPoints,
        serverTime: this.serverTime,
        loadingType: this.loadingType,
        carType: this.carType,
        mobile: this.phone,
        price: 12,
        destPointId: this.targetPoint.uAddrId,
      };
      console.log("orderSubmit>>", orderSubmit);

      let payNonceStr = this.getRandomString(32);
      this.$API.post("/transport/order/submit", orderSubmit).then((res) => {
        console.log(res);
        if (res.code === 20000) {
          const url = "../orderInfo/index?orderId=" + res.data.id;
          wx.navigateTo({ url });
        }
      });
    },
    removePassPoint(index) {
      this.passPoints.splice(index, 1);
    },
    getRandomString(len) {
      let min = 0,
        max = _charStr.length - 1,
        _str = "";
      //判断是否指定长度，否则默认长度为15
      len = len || 15;
      //循环生成字符串
      for (var i = 0, index; i < len; i++) {
        index = RandomIndex(min, max, i);
        _str += _charStr[index];
      }
      return _str;
    },
    showMapSelect() {
      console.log("showMapSelect");
    },
    listTrucksConfig() {
      let _page = this;
      let p = new Promise((resolve, reject) => {
        this.$API.get("/transport/trucks/config").then((res) => {
          if (res.code === 20000) {
            let carTypes = [];
            const list = res.data;
            list.forEach((item, index) => {
              const car = {
                name: item.carName,
                id: item.carType,
                height: item.height,
                width: item.width,
                weight: item.weight,
                img: item.carImg,
                remark: item.remark,
                priceKm: item.priceKm,
                basePrice: item.basePrice,
              };
              carTypes.push(car);
            });
            store.commit("setTrucks", carTypes);
            _page.navList.forEach((item, index) => {
              item.carImg = utils.fileMgrUrl + carTypes[index].img;
            });
            console.log("carTypes[0].remark>>", carTypes[0].remark);
            _page.carRemark = carTypes[0].remark;
            resolve(carTypes);
          } else {
            reject(res);
          }
        });
      });
      p.then((res) => {
        console.log("this.navList res", res);
      }).catch((error) => {
        console.error("error>>", error);
      });
      return p;
    },
    selectMapPoint() {
      let p = new Promise((resolve, reject) => {
        wx.chooseLocation({
          success: function (res) {
            let place_info = {
              longitude: res.longitude,
              latitude: res.latitude,
              addDetail: res.address,
              city: "",
              dist: "",
            };
            qqmapsdk.reverseGeocoder({
              location: {
                latitude: res.latitude, //纬度
                longitude: res.longitude, //经度
              },
              //回调成功显示位置详细信息
              success: function (res1) {
                if (res1.status == 0) {
                  let ad_info = res1.result.ad_info;
                  let format_add = res1.result.formatted_addresses;
                  place_info.city = ad_info.city;
                  place_info.dist = ad_info.district;
                  place_info.addDetail = format_add.recommend;
                }
              },
              fail: function (error) {
                console.error(error);
              },
              complete: function (res) {
                resolve(place_info);
              },
            });
          },
          fail: function (err) {
            console.log(err);
            reject(err);
          },
          complete: function (opt) {
            console.log(opt);
          },
        });
      });

      return p;
    },

    addPassPoint(index) {
      let _page = this;
      let promise = this.selectMapPoint();
      promise
        .then(function (res) {
          let p_point = {
            addr: res.addDetail,
            name: res.city + res.dist,
            coordinate: JSON.stringify({
              lat: res.latitude,
              lon: res.longitude,
            }),

            longitude: res.longitude, //经度
            latitude: res.latitude, //纬度
            city: res.city,
            dist: res.dist,
            addDetail: res.addDetail,
          };
          _page.passPoints.push(p_point);
        })
        .catch(function (error) {
          console.error("error", error);
        });
    },
    endPlaceClick() {
      let _page = this;
      let promise = this.selectMapPoint();

      promise
        .then(function (res) {
          _page.endPlace = {
            longitude: res.longitude,
            latitude: res.latitude,
            city: res.city,
            addDetail: res.addDetail,
          };
          _page.endPlace_s = res.addDetail;
          _page.endPlace_s_s = res.city;
        })
        .catch(function (error) {
          console.error("error", error);
        });
    },
    getLocation() {
      console.log("定位-----");

      let that = this;
      wx.getLocation({
        success: function (res) {
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: res.latitude, //纬度
              longitude: res.longitude, //经度
            },
            //回调成功显示位置详细信息
            success: function (res) {
              //startPlaceName
              if (res.status == 0) {
                let result = res.result;

                let addr_detail = result.address_component;
                that.startPlace.addDetail =
                  addr_detail.district + addr_detail.street_number;

                let location = result.location;
                that.startPlace.longitude = location.lng;
                that.startPlace.latitude = location.lat;
                that.startPlace.city = result.address_component.city;
              }
            },
            //回调失败
            fail: function (res) {
              console.log("回调失败 res", res);
            },
            //成功失败都会执行
            complete: function (res) {
              console.log("执行结束", res);
            },
          });
        },
      });
    },
  },
  mounted() {
    qqmapsdk = new QQMapWX({
      key: utils.qqMApKey,
    });

    this.carType = this.navList[0].id;
  },
  onLoad(options) {
    console.log("options", options);
    console.log("navList>>", this.navList);
    this.getLocation();
  },
  created() {
    console.log("created this.carTypeList>>", this.carTypeList.length);
    if (this.carTypeList.length === 0) {
      let p = this.listTrucksConfig();
      console.log("-------------this.carRemark>>", this.carRemark);
    }
  },
  onShow() {
    let p = utils.checkWxLogin();
    let _page = this;
    p.then(function (res) {
      console.log("p res", res);
      if (res.state) {
        _page.user = res.user;
        _page.token = res.user.token;
      }
    }).catch(function (res) {
      console.warn("res", res);
      if (typeof _page.token === "undefined") {
        const url = "../profile/loginOption/index";
        wx.navigateTo({ url });
      }
    });

    console.log("store.state.trucks>>", store.state.trucks);

    if (this.targetPoint.uAddrId > 0) {
      this.endPlace = this.targetPoint;
      this.endPlace_s = this.targetPoint.addDetail;
      this.endPlace_s_s = this.targetPoint.city;
    }
  },
};
</script>

<style scoped>
.midd-1 {
  margin: 10px 1px;
  display: block;
}
.server-time {
  display: contents;
}
.radio-line {
  margin: 10px 1px;
  display: block;
}
.submit-btn {
  margin-top: 20px;
}
.start-place-click {
  position: absolute;
  top: 10px;
  left: 36px;
  display: block;

  height: 90rpx;
  width: 310rpx;
  z-index: 100;
}
.img-rek {
  margin: 10px 0px 5px 0px;
  display: block;
  text-align: center;
}
</style>
